/*
NAME: 
DESCRIPTION: ;
PARAMETER:
    [
		{
			name : 'step_fliter',
			title : 'Step过滤',
			type : 'LineEdit',
			property : {tool_tip : 'Step过滤'},
		},
		{
			name : 'suffix',
			title : '对比层前缀',
			type : 'LineEdit',
			property : {tool_tip : '对比层前缀'},
		},
		{
            name : 'auto_save',
			title : '自动保存',
            type : 'RadioBox',
            property : {
				item_list:[
					{name:'yes',text:'YES'},
					{name:'no',text:'NO'},
				],
				tool_tip:'是否自动保存料号开关'
			}
        }
	]
	
 VERSION_HISTORY:
	V1.00 2020-05-13 Scott Sun
	    1.新版本
		
 HELP:
 	<html><body bgcolor="#DDECFE">
		<font size="3" color="#003DB2"><p>功能简介</p></font>
		<p> 原稿对比 </p>
		<br>
		<font size="3" color="#003DB2"><p>参数配置</p></font>
		<p> 配置 </p>
		<br>
		<font size="3" color="#003DB2"><p>注意事项</p></font>
		<p> 无 </p>
		<br>
	</body></html>	
*/
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
console.log("==============================>JTG_PUB_orig_compare_aim start");
/* question
    ?
*/
// 引入模块 包
var $ = require('topcam.scriptfunc').argv();
var fs = require('fs');
var _ = require('lodash');
var mode = $.ikm ? "topcam" : "aimdfm";
var IKM = $.ikm; 
if (IKM==undefined ) { IKM = require('topcam.ikm6')($) }
var GEN = $.gen;
var GUI = $.gui || {};
var Job = $.job || $.job_name;
var JobId = $.job_id;
var db = $.db || IKM.db;
var PAR = {}
if ($.par) {
	PAR = $.par
} else if ($.hasOwnProperty('script_parameter')){
	PAR = JSON.parse($.script_parameter);
}
if (mode === "aimdfm") {
	var database = require("topsin.database");
	database.addConnection($.conf.database_conf, "DFM");
	var QDfm = database.query("DFM");
	$.QDfm = QDfm;
	if ($.conf.product_type == "aimdfm") {
		QDfm.updateRow({
			table: "pdm_aimdfm_task",
			data: {
				current_process_title: $.process_title
			},
			where: { id: $.task_id }
		});
	}
}
var Status = 'ok';
var resultData = [];

try {
	var par = PAR;
    var default_par = {  // par默认参数？
		suffix:"org-",
		step_fliter:"unit.+",
		step2:"unit",
		units: "mm",
		auto_save: "no"
	}
	for(var key in default_par){  // 设置默认属性
		if (!par.hasOwnProperty(key) || par[key] == ""){
			par[key] = default_par[key]
		}
	}
	
	if(_.isEmpty(Job)){throw "参数Job不存在"}
	var job = Job.toLowerCase()
	if(!GEN.isJobExists({job:job})){throw "料号"+job+"不存在"}
	if(!GEN.isJobOpen({job:job})){ GEN.openJob({job:job}) }
    if(mode == "aimdfm"){
        if(GEN.checkInout({job:job,mode:"test"}) != 0){ throw "the job check" }
        GEN.checkInout({job:job,mode:"out"});
    }
	
	// 脚本开始
	// 获取board层信息
	var matrix = GEN.getMatrix({job:job})
	var n_layers = Object.keys(matrix).sort(function(a,b){return matrix[a].row - matrix[b].row})
	.filter(function(key){
		var val = matrix[key]
		return val.context == "board"
	})
	if(n_layers.length == 0){throw "can not find layer"}
	// 根据对比层后缀获取原稿层
	var compare_arr = []
	var no_compare_arr = []
	n_layers.forEach(function(layer){
		var org_layer = par.suffix + layer
		if(matrix[org_layer]){
			compare_arr.push({now_layer:layer,org_layer:org_layer,map_layer:layer+"-compare"})
		} else {
			no_compare_arr.push({now_layer:layer,org_layer:org_layer})
		}
	})
	var stepList = GEN.getStepList({job:job})
	if(par.step_fliter != ""){
		var step_reg = new RegExp(par.step_fliter) 
		stepList = stepList.filter(function(v){return step_reg.test(v)})
	}
	if (stepList.length == 0 && par.step2) {
		stepList = GEN.getStepList({job:job}).filter(function (v) {
			var tmpreg = new RegExp(par.step2, "ig");
			return tmpreg.test(v);
		})
	}
	stepList.forEach(function(step){
		GEN.openStep({job:job, name:step})
		GEN.units({type:par.units})
		GEN.clearLayers()
		compare_arr.forEach(function(item){
			if(GEN.isLayerExists({job:job, layer:item.map_layer})){GEN.deleteLayer({job:job,layer:item.map_layer})}
			var diff = GEN.compareLayers({
				layer1:item.now_layer,job2:job,step2:step,layer2:item.org_layer,map_layer:item.map_layer
			});
			if(diff){
				item.res = {status:"NG", layer:item.map_layer}
			} else {
				item.res = "ok";
				GEN.deleteLayer({job:job, layer:item.map_layer})
			}
		})
	})
	// GEN.deleteLayer({job:job,layer:n_layers.map(function(v){return v + "+++"})})
	compare_arr.forEach(function(item){
		if(item.res == "ok"){
			resultData.push( {type: "info", title: item.now_layer+"比对"+item.org_layer+"  ok"})
		} else {
			resultData.push( {type: "error", title: item.now_layer+"比对"+item.org_layer,
				detail: [{desc: _.toString(item.res)}]
		})
		}
	})
	no_compare_arr.forEach(function(item){
		resultData.push( {type: "error", title: item.now_layer+"层未找到其原稿层"+item.org_layer} )
	})
	// 保存 
	if(/yes/ig.test(par.auto_save)){
		GEN.checkInout({job:job,mode:"out"})  // 结束保存料号 关闭料号
		GEN.saveJob({ job: job });
		GEN.checkInout({job:job,mode:"in"})
		GEN.closeJob({job:job})
	} else {
		GEN.checkInout({job:job,mode:"in"})
	}
    console.log("========================JTG_PUB_orig_compare_aim end");
    if (mode === "aimdfm") {
		$.QDfm.updateRow({
			table: "pdm_aimdfm_task",
			data: {
				progress: 33.33
			},
			where: { id: $.task_id }
		});
		if (GEN.hasError()) {
			Status = 'error';
			resultData.push({ type: "error", title: "GEN错误!", detail: [{ desc: _.join(GEN.STATUS, "\n") }] });
			return {
				status: Status,
				result_data: resultData
			};
		} else {
			resultData.push({ type: "info", title: "操作完成, 请注意检查!" });
			return {
				status: Status,
				result_data: resultData
			};
		}
	}else {
		return "Done"
	}
} catch (e) {
	IKM.msg(_.join(GEN.STATUS, "\n"))
	IKM.msg(e)
    Status = 'error';
    resultData.push({type: "error", title: "脚本执行出错!", detail: [{desc: _.toString(e)}]});
    return (mode === "aimdfm") ? {status: Status, result_data: resultData} : "Error";
}